import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_structure/common/config/config_path.dart';
import 'package:flutter_structure/common/widgets/slide_animation.dart';

class Prompt {
  static SlideAnimation? _animationInstance;
  static Timer? _currentTimer; // 用于跟踪当前计时器

  static void show({
    required String message,
    required ThemeData theme,
    bool showIcon = true,
    String position = 'center',
    int durationMilliseconds = 1500,
  }) {
    // 如果已有弹框实例，先关闭它并取消当前计时器
    if (_animationInstance != null) {
      _currentTimer?.cancel(); // 取消现有计时器
      hide();
    }

    Offset beginOffset;
    Offset endOffset = Offset.zero;

    // 根据位置设置动画偏移量
    switch (position.toLowerCase()) {
      case 'top':
        beginOffset = const Offset(0, -1.0); // 从顶部进场
        break;
      case 'bottom':
        beginOffset = const Offset(0, 1.0); // 从底部进场
        break;
      default:
        beginOffset = const Offset(1, 0); // 默认从右侧进场
    }

    // 创建新的动画实例
    _animationInstance = SlideAnimation(
      content: _content(message: message, theme: theme),
      beginOffset: beginOffset,
      endOffset: endOffset,
      position: position,
      dismissOnBackgroundTap: false,
      showOverlay: false,
    );

    // 显示动画
    _animationInstance?.show();

    // 设置新的计时器，确保每次都是独立计时
    _currentTimer = Timer(Duration(milliseconds: durationMilliseconds), () {
      hide();
    });
  }

  static void hide() {
    // 如果动画实例存在，调用关闭并清理计时器
    _animationInstance?.close();
    _animationInstance = null;

    // 清理计时器
    _currentTimer?.cancel();
    _currentTimer = null;
  }

  static Widget _content({
    required String message,
    required ThemeData theme,
    showIcon = false,
  }) {
    return Material(
      color: Colors.transparent,
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(12.0),
          color: theme.scaffoldBackgroundColor,
          boxShadow: [
            BoxShadow(
              color: theme.cardColor,
              offset: const Offset(0, 4),
              blurRadius: 8.0,
              spreadRadius: 0,
            ),
          ],
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            if (showIcon)
              ClipRRect(
                borderRadius: BorderRadius.circular(24.0),
                child: Image.asset(
                  "${AppConfig.assetsMedia}icon.png",
                  width: 24,
                  height: 24,
                ),
              ),
            if (showIcon) const SizedBox(width: 8),
            Text(
              message,
              style: const TextStyle(
                fontSize: 12,
                fontWeight: FontWeight.w500,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
